//
//  UITextField+GFRestrict.m
//  qmtest
//
//  Created by 岳云石 on 2017/3/24.
//  Copyright © 2017年 岳云石. All rights reserved.
//

#import "UITextField+GFRestrict.h"
#import <objc/runtime.h>

static void * GFRestrictTypeKey = &GFRestrictTypeKey;
static void * GFTextRestrictKey = &GFTextRestrictKey;
static void * GFMaxTextLengthKey = &GFMaxTextLengthKey;

@implementation UITextField (GFRestrict)

- (void)setRestrictType:(GFRestrictType)restrictType{
    objc_setAssociatedObject(self, GFRestrictTypeKey, @(restrictType), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    self.textRestrict = [GFTextRestrict textRestrictWithRestrictType:restrictType];
}

- (GFRestrictType)restrictType{
    
    return [objc_getAssociatedObject(self, GFRestrictTypeKey) intValue];

}

- (void)setTextRestrict:(GFTextRestrict *)textRestrict{
    
    if (self.textRestrict) {
        [self removeTarget: self.text action: @selector(textDidChanged:) forControlEvents: UIControlEventEditingChanged];
    }
    textRestrict.maxLength = self.maxTextLength;
    [self addTarget: textRestrict action: @selector(textDidChanged:) forControlEvents: UIControlEventEditingChanged];
    objc_setAssociatedObject(self, GFTextRestrictKey, textRestrict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
}

- (GFTextRestrict *)textRestrict{
    return objc_getAssociatedObject(self, GFTextRestrictKey);
}

- (void)setMaxTextLength:(NSUInteger)maxTextLength{
    
    if (maxTextLength == 0) {
        maxTextLength = NSUIntegerMax;
    }
    
    self.textRestrict.maxLength = maxTextLength;
    
    objc_setAssociatedObject(self, GFMaxTextLengthKey, @(maxTextLength), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSUInteger)maxTextLength{
    NSUInteger maxTextLength = [objc_getAssociatedObject(self, GFMaxTextLengthKey) unsignedIntegerValue];
    if (maxTextLength == 0) {
        self.maxTextLength = NSUIntegerMax;
    }
    return [objc_getAssociatedObject(self, GFMaxTextLengthKey) unsignedIntegerValue];
}

@end
